package jsonutils;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.spring.PropertyPreFilters;
import jsonutils.testbean.User;

/**
 * @author Xiongx
 * @version 1.0
 * @date 2021/7/31 12:26
 * @since JDK 1.8
 */
public class JsonUtils {


    /**
     * SerializerFeature.WriteMapNullValue  包含值为null
     * SerializerFeature.PrettyFormat   默认忽视值不为null
     */

    /**
     * 排除掉不需要的字段
     * @param t
     * @param excludes
     * @param <T>
     * @return
     */
    public static <T> String getJSONandExclude(T t,String [] excludes){
        PropertyPreFilters filters = new PropertyPreFilters();
        PropertyPreFilters.MySimplePropertyPreFilter excludefilter = filters.addFilter();
        excludefilter.addExcludes(excludes);
        return JSONObject.toJSONString(t,excludefilter,SerializerFeature.PrettyFormat);
    }

    /**
     *
     * JSON 只保留需要部分字段
     * @param t
     * @param strings
     * @param <T>
     * @return
     */
    public static <T> String getJSONandIncludString(T t,String[] strings){
        PropertyPreFilters filters = new PropertyPreFilters();
        PropertyPreFilters.MySimplePropertyPreFilter includefilter = filters.addFilter();
        includefilter.addIncludes(strings);
        return JSONObject.toJSONString(t,includefilter,SerializerFeature.PrettyFormat);
    }


    //忽略get + 时间处理，默认是yyyy-MM-dd HH:mm:ss
    public static <T> String getBeanValueString(T t){
        return JSONObject.toJSONString(t, SerializerFeature.IgnoreNonFieldGetter,SerializerFeature.WriteDateUseDateFormat);
    }

    //时间统一处理 或可用 @JSONField(format = "yyyy-MM-dd")
    public static <T> String getBeanValueDate(T t,String formart){
        return JSONObject.toJSONStringWithDateFormat(t,formart,SerializerFeature.WriteDateUseDateFormat);
    }



}
